package camid.main.jmeter;

import java.util.Iterator;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;

import camid.main.ClientFacade;
import camid.test.testobjects.IDelayObject;
import camid.test.testobjects.StatefulDelayObject;


public class CamidJMeterClient2 extends AbstractJavaSamplerClient {

	public static final Long DEFAULT_DELAY = 100L;
	public static final String DEFAULT_NSHOST = "127.0.0.1";
	public static final Integer DEFAULT_NSPORT = 15001;
	
	private String nshost;
	private Integer nsport;
	private Long delay;
	
	private static AtomicInteger objectCounter = new AtomicInteger(0);
	
	private IDelayObject delayObject;
	
	@Override
	public SampleResult runTest(JavaSamplerContext samplerContext) {
		SampleResult result = new SampleResult();
		
		try
		{
			result.sampleStart();
			delayObject.doDelay(delay);
			result.setSuccessful(true);
		}
		catch(Exception e)
		{
			result.setSuccessful(false);
		}
		finally
		{
			result.sampleEnd();
		}
		
		return result;
	}

	private String whoAmI() {
        StringBuilder sb = new StringBuilder();
        sb.append(Thread.currentThread().toString());
        sb.append("@");
        sb.append(Integer.toHexString(hashCode()));
        return sb.toString();
    }
	
	@Override
    public Arguments getDefaultParameters() {
        Arguments params = new Arguments();
        params.addArgument("delay", String.valueOf(DEFAULT_DELAY));
        params.addArgument("host", "127.0.0.1");
        params.addArgument("port", "15001");
        return params;
    }
	
	public void setupTest(JavaSamplerContext context) {
        getLogger().debug(whoAmI() + "\tsetupTest()");
        listParameters(context);

        nshost = context.getParameter("host", DEFAULT_NSHOST);
        nsport = context.getIntParameter("port", DEFAULT_NSPORT);
        delay = context.getLongParameter("delay", DEFAULT_DELAY);
        
        ClientFacade client = ClientFacade.getInstance();
        client.remoteNameService(nshost, nsport);
        delayObject = client.lookupObject(IDelayObject.class, StatefulDelayObject.class, 
        		"delay" + objectCounter.getAndIncrement());
    }
	
	@Override
    public void teardownTest(JavaSamplerContext context) 
	{
        getLogger().debug(whoAmI() + "\tteardownTest()");
    }
	
	private void listParameters(JavaSamplerContext context) 
	{
        if (getLogger().isDebugEnabled()) {
            Iterator<String> argsIt = context.getParameterNamesIterator();
            while (argsIt.hasNext()) 
            {
                String name = argsIt.next();
                getLogger().debug(name + "=" + context.getParameter(name));
            }
        }
    }

}
